<?php
/**
 * 系统设置助手类
 * 提供统一的系统设置获取接口
 */
class SettingsHelper {
    private static $instance = null;
    private $db;
    private $cache = [];

    private function __construct() {
        $this->db = Database::getInstance();
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取系统设置
     */
    public function getSetting($key, $default = '') {
        // 检查缓存
        if (isset($this->cache[$key])) {
            return $this->cache[$key];
        }

        try {
            $result = $this->db->query("SELECT setting_value FROM system_settings WHERE setting_key = ?", [$key]);
            $value = !empty($result) ? $result[0]['setting_value'] : $default;
            
            // 缓存结果
            $this->cache[$key] = $value;
            return $value;
        } catch (Exception $e) {
            error_log("获取系统设置失败: " . $e->getMessage());
            return $default;
        }
    }

    /**
     * 获取网站名称
     */
    public function getSiteName() {
        return $this->getSetting('site_name', 'CDK支付系统');
    }

    /**
     * 获取网站URL
     */
    public function getSiteUrl() {
        return $this->getSetting('site_url', 'http://localhost/cdkpay');
    }

    /**
     * 获取管理员邮箱
     */
    public function getAdminEmail() {
        return $this->getSetting('admin_email', 'admin@example.com');
    }

    /**
     * 获取货币单位
     */
    public function getCurrency() {
        return $this->getSetting('currency', 'CNY');
    }

    /**
     * 获取时区
     */
    public function getTimezone() {
        return $this->getSetting('timezone', 'Asia/Shanghai');
    }

    /**
     * 获取支付配置
     */
    public function getPaymentConfig() {
        return [
            'pid' => $this->getSetting('easypay_pid', '1000'),
            'key' => $this->getSetting('easypay_key', 'your_key_here'),
            'api_url' => $this->getSetting('easypay_api_url', 'https://zf.tuour.com/submit.php'),
            'notify_url' => $this->getSetting('easypay_notify_url', 'http://localhost/cdkpay/notify.php'),
            'return_url' => $this->getSetting('easypay_return_url', 'http://localhost/cdkpay/return.php')
        ];
    }

    /**
     * 清除缓存
     */
    public function clearCache() {
        $this->cache = [];
    }

    /**
     * 保存系统设置
     */
    public function saveSetting($key, $value, $type = 'string', $description = '') {
        try {
            // 使用REPLACE INTO来更新或插入
            $sql = "REPLACE INTO system_settings (setting_key, setting_value, setting_type, description, updated_at) VALUES (?, ?, ?, ?, NOW())";
            $success = $this->db->query($sql, [$key, $value, $type, $description]);
            
            // 清除缓存
            if (isset($this->cache[$key])) {
                unset($this->cache[$key]);
            }
            
            return $success;
        } catch (Exception $e) {
            error_log("保存系统设置失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取所有系统设置
     */
    public function getAllSettings() {
        try {
            $result = $this->db->query("SELECT setting_key, setting_value FROM system_settings");
            $settings = [];
            foreach ($result as $row) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
            return $settings;
        } catch (Exception $e) {
            error_log("获取所有系统设置失败: " . $e->getMessage());
            return [];
        }
    }
}

/**
 * 全局函数：获取系统设置
 */
function getSystemSetting($key, $default = '') {
    return SettingsHelper::getInstance()->getSetting($key, $default);
}

/**
 * 全局函数：获取网站名称
 */
function getSiteName() {
    return SettingsHelper::getInstance()->getSiteName();
}

/**
 * 全局函数：获取网站URL
 */
function getSiteUrl() {
    return SettingsHelper::getInstance()->getSiteUrl();
}
